import { Button, Image, Popconfirm, Space, Table } from 'antd';
import { useEffect, useState } from 'react';
import { DeleteOutlined } from '@ant-design/icons'
import { deleteBanner, getBannerList } from '../../api/banner';
import { useHeight } from '../useHeight';
import { Link } from 'react-router-dom';

type ListProps = {}
interface DataType {
  bannerid: string
  img: string
  alt: string
  link: string
}

export const List = (props: ListProps) => {
  const [bannerList, setBannerList] = useState<DataType[]>([])
  const height = useHeight()

  const [current, setCurrent] = useState<number>(1) // 页码
  const [pageSize, setPageSize] = useState<number>(10) // 每页显示个数

  const getData = async () =>{
    const res = await getBannerList()
    console.log(res.data.data)
    setBannerList(res.data.data)
  }
  useEffect(() => {
    getData()
  }, [])
  return (
    <Space direction='vertical' style={{ width: '100%'}}>
      <Link to="/banner/add">
        <Button type='primary'>添加轮播图</Button>
      </Link>
      <Table 
        dataSource={ bannerList } 
        rowKey="bannerid"
        scroll={{ y: height }}
        bordered
        pagination={{
          current,
          pageSize,
          onChange(page, pageSize) {
            setCurrent(page)
            setPageSize(pageSize)
          }
        }}
      >
        <Table.Column 
          title="序号"
          render={(text, record, index) => { return <span>{ (current - 1) * pageSize + index + 1 }</span>}}
        ></Table.Column>
        <Table.Column
          title="图片"
          dataIndex="img"
          render={ (text) => {return <Image src={text} width={200} height={100} /> }}
        ></Table.Column>
        <Table.Column
          title="提示信息"
          dataIndex="alt"
        ></Table.Column>
        <Table.Column
          title="链接地址"
          dataIndex="link"
        ></Table.Column>
        <Table.Column
          title="操作"
          render={ (text, record: DataType, index) => {return (
            <Space>
             <Popconfirm
                title="确定删除吗?"
                onConfirm={ () => {
                  deleteBanner({ bannerid: record.bannerid }).then(() => {
                    getData()
                  })
                }}
                onCancel={() => {}}
                okText="确定"
                cancelText="再想想"
              >
                <Button danger shape="circle" icon={<DeleteOutlined />} />
              </Popconfirm>
            </Space>
          ) }}
        ></Table.Column>
      </Table>
    </Space>
  );
}
